package zzps.exeed.web.servlet;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import zzps.exeed.kernel.ExeedConfig;
import zzps.exeed.kernel.core.AppContext;
import zzps.exeed.web.handle.ContextHolder;
import zzps.exeed.web.handle.HandlerManager;
import zzps.exeed.web.transformer.InputOutputTransformerManager;

import java.io.IOException;

public class ExeedServlet extends HttpServlet {

    HandlerManager handlerManager = HandlerManager.get();
    AppContext appContext;
    InputOutputTransformerManager inputOutputTransformerManager = InputOutputTransformerManager.get();

    public ExeedServlet(AppContext appContext) {
        this.appContext = appContext;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }
    private void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        ExeedServletContext context = new ExeedServletContext(request, response);
        ContextHolder.set(context);
        try {
            handlerManager.handle(context);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }finally {
            ContextHolder.remove();
        }
    }
}
